package unimelb.filesync.client.protocol;

import java.security.PublicKey;

import javax.crypto.SecretKey;

import unimelb.filesync.common.crypto.CryptoUtils;
import unimelb.filesync.common.message.NetworkMessage;
import unimelb.filesync.common.message.SecretKeyMsg;
import unimelb.filesync.common.misc.ProtocolContext;
import unimelb.filesync.common.network.NetworkConnection;
import unimelb.filesync.common.network.NetworkService;
import unimelb.filesync.common.network.RsaEncryptedNetworkConnection;
import unimelb.filesync.common.protocol.IFileSyncPhase;

public class SendSecretKeyPhase implements IFileSyncPhase {

    private final ProtocolContext context;

    private final CryptoUtils cryptoUtils;

    private final NetworkService networkService;

    public SendSecretKeyPhase(ProtocolContext context) {
        super();
        this.context = context;
        this.cryptoUtils = new CryptoUtils();
        this.networkService = new NetworkService();
    }

    @Override
    public void execute() {
        System.out.println("Sending secret key and init vector");

        final NetworkConnection unsecuredConnection = context.getObject(ProtocolContext.HOT_LINE_CONNECTION);
        final PublicKey publicKey = context.getObject(ProtocolContext.PUBLIC_KEY);
        final NetworkConnection securedConnection = new RsaEncryptedNetworkConnection(unsecuredConnection, publicKey);
        
        final SecretKey secretKey = context.getObject(ProtocolContext.SECRET_KEY);

        final SecretKeyMsg msg = new SecretKeyMsg(cryptoUtils.encodeSecretKey(secretKey));
        networkService.writeMessage(NetworkMessage.createSecretKeyMsg(msg), securedConnection);
    }

}
